<template>
  <div class="employee-location-picker">
    <!-- 显示方式切换和内容区域 -->
    <div class="location-header">
      <a-radio-group :value="viewMode" @change="e => viewMode = e.target.value" button-style="solid">
        <a-radio-button value="map">
          <environment-outlined />
          地图模式
        </a-radio-button>
        <a-radio-button value="list">
          <unordered-list-outlined />
          列表模式
        </a-radio-button>
      </a-radio-group>
    </div>

    <!-- 地图模式 -->
    <div v-if="viewMode === 'map'" class="map-container">
      <div class="map-header">
        <h4 style="margin: 0 0 12px 0; color: #1890ff;">
          📍 以客户为中心的地图视图
          <small style="color: #666; font-weight: normal; margin-left: 8px;">
            客户位置: {{ customerAddress || '加载中...' }}
          </small>
        </h4>
      </div>
      
      <div class="map-controls">
        <a-space>
          <a-button type="primary" @click="getCurrentLocation" :loading="locationLoading">
            <template #icon><aim-outlined /></template>
            定位当前位置
          </a-button>
          <a-button @click="refreshEmployeeLocations" :loading="employeeLoading">
            <template #icon><reload-outlined /></template>
            刷新员工位置
          </a-button>
          <a-button type="primary" @click="relocateCustomer" :loading="locationLoading">
            <template #icon><environment-outlined /></template>
            重新定位客户地址
          </a-button>
          <a-button @click="adjustMapCenterIntelligently" title="以客户为中心，根据员工距离智能调整地图视角">
            <template #icon><eye-outlined /></template>
            客户视角
          </a-button>
          <a-button @click="showDistanceCircles" title="以客户为中心显示距离圈，帮助分析员工分布">
            <template #icon><dot-chart-outlined /></template>
            客户距离圈
          </a-button>
          <a-button @click="toggleCustomerToEmployeeLines" title="显示/隐藏客户到员工的连线和距离">
            <template #icon><line-chart-outlined /></template>
            {{ customerToEmployeeLines.length > 0 ? '隐藏连线' : '显示连线' }}
          </a-button>
          <a-button @click="validateCoordinates">
            <template #icon><search-outlined /></template>
            坐标验证
          </a-button>
          <a-divider type="vertical" />
          <a-select :value="mapFilter" @change="val => mapFilter = val" placeholder="筛选显示" style="width: 150px">
            <a-select-option value="all">显示全部</a-select-option>
            <a-select-option value="available">仅空闲员工</a-select-option>
            <a-select-option value="nearby">附近员工</a-select-option>
          </a-select>
        </a-space>
      </div>
      
      <div class="map-view" ref="mapContainer"></div>
      
      <!-- 地图图例 -->
      <div class="map-legend">
        <div class="legend-item">
          <span class="legend-icon customer"></span>
          <span class="legend-text">客户位置</span>
        </div>
        <div class="legend-item">
          <span class="legend-icon employee available"></span>
          <span class="legend-text">空闲员工</span>
        </div>
        <div class="legend-item">
          <span class="legend-icon employee busy"></span>
          <span class="legend-text">忙碌员工</span>
        </div>
        <div class="legend-item">
          <span class="legend-icon employee selected"></span>
          <span class="legend-text">已选员工</span>
        </div>
        <div class="legend-info">
          <small style="color: #666; margin-left: 16px;">
            💡 提示: 以客户为中心显示，点击标记查看详细信息。使用"客户视角"调整视野，"客户距离圈"分析分布，"显示连线"查看距离
          </small>
        </div>
      </div>
    </div>

    <!-- 列表模式 -->
    <div v-if="viewMode === 'list'" class="list-container">
      <div class="list-controls">
        <a-space>
          <a-input-search
            :value="searchKeyword"
            @change="e => searchKeyword = e.target.value"
            placeholder="搜索员工姓名、部门"
            style="width: 300px"
            @search="handleSearch"
            allow-clear
          />
          <a-select :value="statusFilter" @change="val => statusFilter = val" placeholder="状态筛选" style="width: 120px">
            <a-select-option value="">全部状态</a-select-option>
            <a-select-option value="available">空闲</a-select-option>
            <a-select-option value="busy">忙碌</a-select-option>
          </a-select>
        </a-space>
      </div>

      <a-list
        :data-source="filteredEmployees"
        :pagination="{ pageSize: 10, showSizeChanger: true }"
        class="employee-list"
      >
        <template #renderItem="{ item }">
            <a-list-item
              :class="{
                'selected-employee': isEmployeeSelected(item.id),
                'assignee-selected': selectedAssignee === item.id,
                'collaborator-selected': selectedCollaborators.includes(item.id)
              }"
              @click="handleEmployeeClick(item)"
            >
              <!-- 选择状态标识 -->
              <template v-if="selectedAssignee === item.id || selectedCollaborators.includes(item.id)" #extra>
                <a-space direction="vertical" size="small">
                  <a-tag v-if="selectedAssignee === item.id" color="blue">
                    <user-outlined />
                    负责人
                  </a-tag>
                  <a-tag v-if="selectedCollaborators.includes(item.id)" color="green">
                    <team-outlined />
                    协同人
                  </a-tag>
                </a-space>
              </template>
            <a-list-item-meta>
              <template #avatar>
                <a-avatar :src="item.avatar" :style="{ backgroundColor: getAvatarColor(item.status) }">
                  {{ item.realName?.charAt(0) }}
                </a-avatar>
              </template>
              <template #title>
                <div class="employee-title">
                  <span class="employee-name">{{ item.realName }}</span>
                  <a-tag :color="getStatusColor(item.status)" size="small">
                    {{ getStatusText(item.status) }}
                  </a-tag>
                  <!-- 显示已分配状态 -->
                  <a-tag v-if="currentAssignedUsers.includes(item.id)" color="blue" size="small">
                    {{ getCurrentExecutorRole(item.id) }}
                  </a-tag>
                  <!-- 显示已拒绝状态 -->
                  <a-tag v-if="getRejectedInfo(item.id)" color="red" size="small">
                    已拒绝
                  </a-tag>
                </div>
              </template>
              <template #description>
                <div class="employee-info">
                  <div class="info-row">
                    <team-outlined />
                    <span>{{ item.deptName }}</span>
                  </div>
                  <div class="info-row">
                    <phone-outlined />
                    <span>{{ item.mobile }}</span>
                  </div>
                  <div class="info-row">
                    <environment-outlined />
                    <span>距离客户: {{ item.distance || (item.hasValidLocation ? '计算中...' : '无位置信息') }}</span>
                  </div>
                  <!-- 显示拒绝理由 -->
                  <div v-if="getRejectedInfo(item.id)" class="info-row rejected-info">
                    <exclamation-circle-outlined style="color: #ff4d4f;" />
                    <span style="color: #ff4d4f;">
                      拒绝理由: {{ getRejectedInfo(item.id)?.rejectReason || '未填写' }}
                    </span>
                  </div>
                  <div v-if="getRejectedInfo(item.id)?.rejectTime" class="info-row rejected-time">
                    <clock-circle-outlined style="color: #8c8c8c;" />
                    <span style="color: #8c8c8c; font-size: 12px;">
                      拒绝时间: {{ formatDateTime(getRejectedInfo(item.id).rejectTime) }}
                    </span>
                  </div>
                  <!-- 显示冲突工单 -->
                  <div v-if="item.status === 'busy' && item.conflictingWorkOrders && item.conflictingWorkOrders.length > 0" class="info-row conflicting-workorders">
                    <exclamation-circle-outlined style="color: #faad14;" />
                    <span style="color: #faad14; font-size: 12px;">
                      时间冲突工单: {{ item.conflictingWorkOrders.join(', ') }}
                    </span>
                  </div>
                </div>
              </template>
            </a-list-item-meta>
            <template #actions>
              <a-space>
                <!-- 查看日程按钮 -->
                <a-button 
                  size="small"
                  type="dashed"
                  @click.stop="$emit('view-schedule', item)"
                >
                  <template #icon><calendar-outlined /></template>
                  日程
                </a-button>
                
                <!-- 选择按钮组 -->
                <a-space v-if="selectionMode === 'assignee'" size="small">
                  <!-- 负责人按钮 -->
                  <a-button 
                    :type="props.selectedAssignee === item.id ? 'primary' : 'default'"
                    size="small"
                    @click.stop="handleSelectAsAssignee(item)"
                    :disabled="props.selectedAssignee === item.id"
                  >
                    <user-outlined />
                    {{ props.selectedAssignee === item.id ? '已是负责人' : '选为负责人' }}
                  </a-button>
                  
                  <!-- 协同人员按钮 -->
                  <a-button 
                    :type="props.selectedCollaborators.includes(item.id) ? 'primary' : 'default'"
                    size="small"
                    @click.stop="handleSelectAsCollaborator(item)"
                    :disabled="props.selectedCollaborators.includes(item.id)"
                  >
                    <team-outlined />
                    {{ props.selectedCollaborators.includes(item.id) ? '已是协同人' : '选为协同人' }}
                  </a-button>
                </a-space>
                
                <!-- 非assignee模式的按钮 -->
                <a-button 
                  v-else
                  type="primary" 
                  size="small"
                  disabled
                >
                  {{ getSelectButtonText(item) }}
                </a-button>
              </a-space>
            </template>
          </a-list-item>
        </template>
      </a-list>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { message } from 'ant-design-vue';
import {
  EnvironmentOutlined,
  UnorderedListOutlined,
  AimOutlined,
  ReloadOutlined,
  EyeOutlined,
  DotChartOutlined,
  LineChartOutlined,
  SearchOutlined,
  TeamOutlined,
  PhoneOutlined,
  ExclamationCircleOutlined,
  ClockCircleOutlined,
  CalendarOutlined,
  UserOutlined,
} from '@ant-design/icons-vue';
// @ts-ignore
import { loadAMap, setSecurityConfig } from '@/utils/map-config';
// @ts-ignore
import Api from '@/api/';

// 组件Props定义
interface Props {
  customerLocation: {
    lng: number;
    lat: number;
  };
  customerAddress: string;
  selectedAssignee?: string;
  selectedCollaborators?: string[];
  currentAssignedUsers?: string[];
  rejectedUsers?: any[];
  currentExecutors?: any[];
  workOrderId?: string;
  startTime?: string;
  endTime?: string;
  selectionMode?: 'assignee' | 'pool' | 'provider' | 'auto';
}

const props = withDefaults(defineProps<Props>(), {
  selectedAssignee: '',
  selectedCollaborators: () => [],
  currentAssignedUsers: () => [],
  rejectedUsers: () => [],
  currentExecutors: () => [],
  workOrderId: '',
  startTime: '',
  endTime: '',
  selectionMode: 'assignee'
});

// 组件Emits定义
interface Emits {
  (e: 'update:selectedAssignee', value: string): void;
  (e: 'update:selectedCollaborators', value: string[]): void;
  (e: 'select-assignee', employee: any): void;
  (e: 'select-collaborator', employee: any): void;
  (e: 'view-schedule', employee: any): void;
  (e: 'employees-loaded', employees: any[]): void;
  (e: 'location-geocoded', location: { lng: number; lat: number }): void;
}

const emit = defineEmits<Emits>();

// 地图相关
let map: any = null;
let AMap: any = null;
const mapContainer = ref<HTMLElement | null>(null);
const locationLoading = ref(false);
const employeeLoading = ref(false);

// 响应式数据
const viewMode = ref('list');
const searchKeyword = ref('');
const statusFilter = ref('');
const mapFilter = ref('all');
const allEmployees = ref<any[]>([]);

// 存储连线和距离标签的数组
let customerToEmployeeLines: any[] = [];
let distanceLabels: any[] = [];

// 计算属性
const filteredEmployees = computed(() => {
  let employees = [...allEmployees.value];

  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    employees = employees.filter(emp => 
      emp.realName.toLowerCase().includes(keyword) ||
      emp.deptName.toLowerCase().includes(keyword)
    );
  }

  // 状态过滤
  if (statusFilter.value) {
    employees = employees.filter(emp => emp.status === statusFilter.value);
  }

  return employees;
});

// 检查地图是否就绪
const checkMapReady = () => {
  if (!AMap) {
    console.warn('高德地图API未加载');
    return false;
  }
  if (!map) {
    console.warn('地图实例未初始化');
    return false;
  }
  return true;
};

// 客户位置验证和地理编码
const handleCustomerLocationValidation = async () => {
  const isDefaultLocation = props.customerLocation.lng === 116.397428 && 
                           props.customerLocation.lat === 39.90923;
  
  if (isDefaultLocation && props.customerAddress && props.customerAddress.trim() !== '') {
    console.log('检测到默认坐标，尝试根据地址进行地理编码:', props.customerAddress);
    try {
      await performGeocoding(props.customerAddress);
    } catch (error) {
      console.warn('地理编码失败:', error);
    }
  }
};

// 执行地理编码
const performGeocoding = async (address: string) => {
  if (!AMap || !address) return;
  
  return new Promise((resolve, reject) => {
    AMap.plugin('AMap.Geocoder', () => {
      const geocoder = new AMap.Geocoder({
        city: '全国',
        radius: 1000,
        extensions: 'all'
      });
      
      geocoder.getLocation(address, (status: string, result: any) => {
        if (status === 'complete' && result.geocodes && result.geocodes.length > 0) {
          const location = result.geocodes[0].location;
          
          console.log('组件内地理编码成功:', address, '坐标:', location.lng, location.lat);
          
          // 通知父组件坐标已更新
          const newLocation = {
            lng: parseFloat(location.lng.toFixed(6)),
            lat: parseFloat(location.lat.toFixed(6))
          };
          
          console.log('发送地理编码事件到父组件:', newLocation);
          // 发送事件通知父组件
          emit('location-geocoded', newLocation);
          
          resolve(location);
        } else {
          console.warn('组件内地理编码失败:', status, result);
          reject(new Error('地理编码失败'));
        }
      });
    });
  });
};

// 初始化地图
const initMap = async () => {
  if (!mapContainer.value) return;

  try {
    setSecurityConfig();
    AMap = await loadAMap();

    const customerLocation = props.customerLocation;
    console.log('地图初始化 - 客户位置:', customerLocation);

    map = new AMap.Map(mapContainer.value, {
      viewMode: '3D',
      zoom: 9,
      center: [customerLocation.lng, customerLocation.lat],
      mapStyle: 'amap://styles/light',
      resizeEnable: true,
      rotateEnable: false,
      pitchEnable: false,
      buildingAnimation: false,
      expandZoomRange: true,
      zooms: [4, 20],
      features: ['bg', 'road', 'building', 'point'],
      showIndoorMap: false,
      skyColor: '#ffffff',
      animateEnable: true,
      jogEnable: false,
      scrollWheel: true,
      doubleClickZoom: true,
      keyboardEnable: false,
      isHotspot: false,
      defaultCursor: 'pointer',
      touchZoom: true,
      touchZoomCenter: 1
    });

    // 添加比例尺控件
    const scale = new AMap.Scale({ 
      position: 'LB',
      visible: true,
      offset: [10, 10]
    });
    map.addControl(scale);

    // 加载并添加缩放控件插件
    AMap.plugin(['AMap.ToolBar'], () => {
      const toolBar = new AMap.ToolBar({
        visible: true,
        onlyInstanceVisible: false,
        position: 'RT',
        offset: [10, 10],
        autoPosition: false,
        locate: true,
        noIpLocate: false,
        locationMarker: true,
        useNative: false
      });
      map.addControl(toolBar);
    });

    // 地图加载完成后的处理
    map.on('complete', async () => {
      console.log('地图加载完成，确保以客户为中心');
      
      // 检查客户位置是否需要地理编码
      await handleCustomerLocationValidation();
      
      const exactCustomerCenter = new AMap.LngLat(props.customerLocation.lng, props.customerLocation.lat);
      map.setCenter(exactCustomerCenter);
      
      addCustomerMarker();
      await loadEmployeeLocations();
    });

    // 监听地图缩放事件
    map.on('zoomend', () => {
      const zoom = map.getZoom();
      optimizeMarkersForZoom(zoom);
    });

  } catch (error) {
    console.error('地图初始化失败:', error);
    message.error('地图初始化失败，请检查网络连接');
  }
};

// 加载员工位置数据
const loadEmployeeLocations = async () => {
  try {
    employeeLoading.value = true;
    
    const availabilityParams = {
      startTime: props.startTime ? new Date(props.startTime).toISOString() : null,
      endTime: props.endTime ? new Date(props.endTime).toISOString() : null,
      excludeWorkOrderId: props.workOrderId
    };
    
    const userAvailabilityResult = await Api.workOrder.userAvailability(availabilityParams);
    const items = userAvailabilityResult || [];
    
    const processedEmployees = items.map(user => {
      const hasValidLocation = user.hasValidLocation && 
                             user.addressLng && 
                             user.addressLat && 
                             typeof user.addressLng === 'number' && 
                             typeof user.addressLat === 'number' &&
                             !isNaN(user.addressLng) && 
                             !isNaN(user.addressLat);
      
      return {
        id: user.id,
        realName: user.realName || user.userName,
        deptName: user.deptName || '未分配',
        mobile: user.mobile || '',
        status: user.status || 'available',
        skills: [],
        location: hasValidLocation ? {
          lng: user.addressLng,
          lat: user.addressLat
        } : null,
        avatar: user.avatar || '',
        email: user.email || '',
        roles: user.roles || [],
        address: user.address || '',
        hasValidLocation: hasValidLocation,
        conflictingWorkOrders: user.conflictingWorkOrders || []
      };
    });

    const employeesWithValidLocation = processedEmployees.filter(emp => emp.hasValidLocation);
    const employeesWithoutLocation = processedEmployees.filter(emp => !emp.hasValidLocation);
    
    // 计算距离
    const employeesWithDistance = employeesWithValidLocation.map(employee => {
      const distance = calculateDistance(employee.location, props.customerLocation);
      return {
        ...employee,
        distance: distance
      };
    });

    const employeesWithoutDistance = employeesWithoutLocation.map(employee => ({
      ...employee,
      distance: ''
    }));

    const finalEmployees = [...employeesWithDistance, ...employeesWithoutDistance];
    allEmployees.value = finalEmployees;
    
    // 通知父组件员工数据已加载
    emit('employees-loaded', finalEmployees);
    
    // 在地图上添加员工标记
    if (map && AMap && employeesWithValidLocation.length > 0) {
      addEmployeeMarkers(employeesWithDistance);
      
      setTimeout(() => {
        adjustMapCenterIntelligently();
      }, 1000);
    }

  } catch (error) {
    console.error('加载员工位置失败:', error);
    message.error('加载员工位置失败');
    
    // 使用备用数据
    const fallbackEmployees = [
      {
        id: 'fallback-1',
        realName: '系统管理员',
        deptName: '技术部',
        mobile: '13800138000',
        status: 'available',
        skills: ['系统维护'],
        location: { lng: 116.405, lat: 39.905 },
        avatar: '',
        address: '北京市朝阳区',
        distance: '约1.2公里',
        hasValidLocation: true
      }
    ];
    
    allEmployees.value = fallbackEmployees;
    
  } finally {
    employeeLoading.value = false;
  }
};

// 计算两点之间的距离
const calculateDistance = (point1: { lng: number; lat: number }, point2: { lng: number; lat: number }) => {
  if (!AMap) {
    return '计算中...';
  }
  
  try {
    if (!point1 || !point2 || 
        typeof point1.lng !== 'number' || typeof point1.lat !== 'number' ||
        typeof point2.lng !== 'number' || typeof point2.lat !== 'number') {
      return '坐标无效';
    }
    
    const lngLat1 = new AMap.LngLat(point1.lng, point1.lat);
    const lngLat2 = new AMap.LngLat(point2.lng, point2.lat);
    const distance = lngLat1.distance(lngLat2);
    
    if (isNaN(distance) || distance < 0) {
      return '计算异常';
    }
    
    if (distance < 1000) {
      return `${Math.round(distance)}米`;
    } else {
      return `${(distance / 1000).toFixed(1)}公里`;
    }
  } catch (error) {
    console.error('距离计算失败:', error);
    return '计算失败';
  }
};

// 添加客户位置标记
const addCustomerMarker = () => {
  if (!checkMapReady()) {
    return;
  }

  const exactPosition = new AMap.LngLat(
    props.customerLocation.lng, 
    props.customerLocation.lat
  );

  try {
    const customerMarker = new AMap.Marker({
      position: exactPosition,
      icon: createCustomerIcon(),
      title: `客户位置`,
      anchor: 'bottom-center',
      zIndex: 100,
      clickable: true
    });

    const infoWindowContent = `
      <div style="padding: 10px; min-width: 200px;">
        <h4 style="margin: 0 0 8px 0; color: #1890ff; font-size: 14px;">
          <span style="color: #ff4d4f; margin-right: 6px;">📍</span>
          客户位置
        </h4>
        <div style="margin-bottom: 6px; font-size: 12px;">
          <strong style="color: #595959;">地址：</strong>
          <span style="color: #262626;">${props.customerAddress}</span>
        </div>
        <div style="text-align: center; padding-top: 6px; border-top: 1px solid #f0f0f0; margin-top: 6px;">
          <small style="color: #8c8c8c; font-size: 11px;">点击关闭</small>
        </div>
      </div>
    `;

    const infoWindow = new AMap.InfoWindow({
      content: infoWindowContent,
      offset: new AMap.Pixel(20, -5),
      closeWhenClickMap: true,
      autoMove: true
    });

    customerMarker.on('click', () => {
      infoWindow.open(map, customerMarker.getPosition());
    });

    map.add(customerMarker);
    
  } catch (error) {
    console.error('添加客户标记失败:', error);
    message.error('添加客户标记失败');
  }
};

// 创建客户图标
const createCustomerIcon = () => {
  const iconSize = 36;
  const iconHtml = `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 48" width="${iconSize}" height="${iconSize * 4/3}">
      <ellipse cx="18" cy="46" rx="8" ry="2" fill="rgba(255, 77, 79, 0.3)"/>
      <path d="M18 2C11.477 2 6 7.477 6 14c0 9 12 30 12 30s12-21 12-30c0-6.523-4.477-12-12-12z" 
            fill="#ff4d4f" stroke="#fff" stroke-width="2"/>
      <circle cx="18" cy="14" r="6" fill="#fff"/>
      <path d="M18 10c-2.2 0-4 1.8-4 4s1.8 4 4 4 4-1.8 4-4-1.8-4-4-4z" fill="#ff4d4f"/>
    </svg>
  `;
  
  return new AMap.Icon({
    image: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(iconHtml),
    size: new AMap.Size(iconSize, iconSize * 4/3),
    imageSize: new AMap.Size(iconSize, iconSize * 4/3),
    imageOffset: new AMap.Pixel(0, 0)
  });
};

// 创建员工图标
const createEmployeeIcon = (status: string) => {
  const color = status === 'available' ? '#52c41a' : status === 'busy' ? '#faad14' : '#1890ff';
  const iconSize = 28;
  const iconHtml = `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="${iconSize}" height="${iconSize}">
      <circle cx="16" cy="30" r="6" fill="rgba(0,0,0,0.1)"/>
      <circle cx="16" cy="16" r="14" fill="${color}" stroke="#fff" stroke-width="2"/>
      <path fill="#fff" d="M16 8c1.5 0 2.5 1 2.5 2.5S17.5 13 16 13s-2.5-1-2.5-2.5S14.5 8 16 8zm0 7c2.5 0 5 1.5 5 3v2H11v-2c0-1.5 2.5-3 5-3z"/>
    </svg>
  `;
  
  return new AMap.Icon({
    image: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(iconHtml),
    size: new AMap.Size(iconSize, iconSize),
    imageSize: new AMap.Size(iconSize, iconSize),
    imageOffset: new AMap.Pixel(0, 0)
  });
};

// 在地图上添加员工标记
const addEmployeeMarkers = (employees: any[]) => {
  if (!checkMapReady() || !employees || employees.length === 0) {
    return;
  }

  const allMarkers: any[] = [];
  let successCount = 0;
  let errorCount = 0;
  
  clearCustomerToEmployeeLines();
  
  const customerLocation = props.customerLocation;
  const customerCenter = new AMap.LngLat(customerLocation.lng, customerLocation.lat);
  
  employees.forEach(employee => {
    if (!employee.location || 
        typeof employee.location.lng !== 'number' || 
        typeof employee.location.lat !== 'number' ||
        !employee.hasValidLocation) {
      errorCount++;
      return;
    }

    try {
      const exactPosition = new AMap.LngLat(employee.location.lng, employee.location.lat);
      
      const marker = new AMap.Marker({
        position: exactPosition,
        icon: createEmployeeIcon(employee.status),
        title: `员工: ${employee.realName}`,
        anchor: 'center',
        zIndex: 50,
        clickable: true
      });

      // 为员工标记添加点击事件
      marker.on('click', () => {
        const employeeInfoContent = `
          <div style="padding: 12px; min-width: 280px;">
            <h4 style="margin: 0 0 8px 0; color: #1890ff; font-size: 14px;">
              👤 ${employee.realName}
            </h4>
            <div style="margin-bottom: 4px; font-size: 12px;">
              <strong style="color: #595959;">部门：</strong><span style="color: #262626;">${employee.deptName}</span>
            </div>
            <div style="margin-bottom: 4px; font-size: 12px;">
              <strong style="color: #595959;">电话：</strong><a href="tel:${employee.mobile}" style="color: #1890ff;">${employee.mobile}</a>
            </div>
            <div style="margin-bottom: 4px; font-size: 12px;">
              <strong style="color: #595959;">状态：</strong><span style="color: ${getStatusColor(employee.status)};">${getStatusText(employee.status)}</span>
            </div>
            <div style="margin-bottom: 4px; font-size: 12px;">
              <strong style="color: #595959;">距离客户：</strong><span style="color: #1890ff; font-weight: 500;">${employee.distance}</span>
            </div>
            ${employee.address ? `<div style="margin-bottom: 4px; font-size: 12px;">
              <strong style="color: #595959;">地址：</strong><span style="color: #262626;">${employee.address}</span>
            </div>` : ''}
            
            ${props.selectionMode === 'assignee' ? `
            <div style="border-top: 1px solid #f0f0f0; padding-top: 8px; margin-top: 8px;">
              <div style="display: flex; gap: 8px; margin-bottom: 8px;">
                <button 
                  onclick="window.selectAsAssigneeFromMap('${employee.id}')"
                  style="
                    flex: 1;
                    padding: 6px 12px; 
                    border: 1px solid #1890ff; 
                    background: ${props.selectedAssignee === employee.id ? '#1890ff' : '#fff'}; 
                    color: ${props.selectedAssignee === employee.id ? '#fff' : '#1890ff'}; 
                    border-radius: 4px; 
                    cursor: ${props.selectedAssignee === employee.id ? 'not-allowed' : 'pointer'}; 
                    font-size: 12px;
                    font-weight: 500;
                    opacity: ${props.selectedAssignee === employee.id ? '0.6' : '1'};
                  "
                  ${props.selectedAssignee === employee.id ? 'disabled' : ''}
                >
                  👤 ${props.selectedAssignee === employee.id ? '已是负责人' : '选为负责人'}
                </button>
                <button 
                  onclick="window.selectAsCollaboratorFromMap('${employee.id}')"
                  style="
                    flex: 1;
                    padding: 6px 12px; 
                    border: 1px solid #52c41a; 
                    background: ${props.selectedCollaborators.includes(employee.id) ? '#52c41a' : '#fff'}; 
                    color: ${props.selectedCollaborators.includes(employee.id) ? '#fff' : '#52c41a'}; 
                    border-radius: 4px; 
                    cursor: ${props.selectedCollaborators.includes(employee.id) ? 'not-allowed' : 'pointer'}; 
                    font-size: 12px;
                    font-weight: 500;
                    opacity: ${props.selectedCollaborators.includes(employee.id) ? '0.6' : '1'};
                  "
                  ${props.selectedCollaborators.includes(employee.id) ? 'disabled' : ''}
                >
                  👥 ${props.selectedCollaborators.includes(employee.id) ? '已是协同人' : '选为协同人'}
                </button>
              </div>
             
            </div>
            ` : `
            <div style="border-top: 1px solid #f0f0f0; padding-top: 8px; margin-top: 8px;">
              <div style="text-align: center; color: #8c8c8c; font-size: 12px;">
                当前派单方式不支持选择人员
              </div>
            </div>
            `}
            
            <div style="text-align: center; padding-top: 6px; margin-top: 6px;">
              <small style="color: #8c8c8c; font-size: 10px;">点击关闭</small>
            </div>
          </div>
        `;
        
        const employeeInfoWindow = new AMap.InfoWindow({
          content: employeeInfoContent,
          offset: new AMap.Pixel(20, -5),
          closeWhenClickMap: true,
          autoMove: true
        });
        
        employeeInfoWindow.open(map, marker.getPosition());
      });

      map.add(marker);
      allMarkers.push(marker);
      
      addCustomerToEmployeeLine(customerCenter, exactPosition, employee.distance, employee.realName);
      
      successCount++;
      
    } catch (error) {
      console.error(`添加员工标记失败 ${employee.realName}:`, error);
      errorCount++;
    }
  });
  
  if (errorCount > 0) {
    message.warning(`部分员工位置添加失败 (${errorCount}/${employees.length})`);
  }
  
  if (allMarkers.length > 0) {
    try {
      autoFitMapView(allMarkers);
    } catch (error) {
      console.error('自动调整地图视野失败:', error);
    }
  }
};

// 添加客户到员工的连线
const addCustomerToEmployeeLine = (customerPosition: any, employeePosition: any, distance: string, employeeName: string) => {
  try {
    const polyline = new AMap.Polyline({
      path: [customerPosition, employeePosition],
      strokeColor: '#1890ff',
      strokeWeight: 2,
      strokeOpacity: 0.6,
      strokeStyle: 'dashed',
      zIndex: 10
    });
    
    map.add(polyline);
    customerToEmployeeLines.push(polyline);
    
    const midLng = (customerPosition.lng + employeePosition.lng) / 2;
    const midLat = (customerPosition.lat + employeePosition.lat) / 2;
    const midPosition = new AMap.LngLat(midLng, midLat);
    
    const distanceLabel = new AMap.Text({
      text: distance,
      position: midPosition,
      style: {
        fontSize: '11px',
        fontWeight: 'bold',
        color: '#1890ff',
        backgroundColor: 'rgba(255,255,255,0.9)',
        padding: '2px 6px',
        borderRadius: '3px',
        border: '1px solid #1890ff',
        textAlign: 'center',
        boxShadow: '0 1px 3px rgba(0,0,0,0.2)'
      },
      zIndex: 15
    });
    
    map.add(distanceLabel);
    distanceLabels.push(distanceLabel);
    
  } catch (error) {
    console.error(`添加连线失败 ${employeeName}:`, error);
  }
};

// 清除连线
const clearCustomerToEmployeeLines = () => {
  customerToEmployeeLines.forEach(line => {
    if (map && line) {
      map.remove(line);
    }
  });
  customerToEmployeeLines = [];
  
  distanceLabels.forEach(label => {
    if (map && label) {
      map.remove(label);
    }
  });
  distanceLabels = [];
};

// 切换连线显示
const toggleCustomerToEmployeeLines = () => {
  if (customerToEmployeeLines.length === 0) {
    const existingCircles = map.getAllOverlays('circle');
    const existingTexts = map.getAllOverlays('text');
    existingCircles.forEach(circle => map.remove(circle));
    existingTexts.forEach(text => map.remove(text));
    
    loadEmployeeLocations();
    message.info('正在显示客户到员工的连线和距离...');
  } else {
    clearCustomerToEmployeeLines();
    message.info('已隐藏客户到员工的连线');
  }
};

// 自动调整地图视野
const autoFitMapView = (employeeMarkers: any[]) => {
  if (!checkMapReady()) {
    return;
  }
  
  try {
    const customerLocation = props.customerLocation;
    const customerCenter = new AMap.LngLat(customerLocation.lng, customerLocation.lat);
    
    map.setCenter(customerCenter);
    
    if (!employeeMarkers || employeeMarkers.length === 0) {
      map.setZoom(9);
      return;
    }
    
    const allDistances = [];
    
    employeeMarkers.forEach((marker) => {
      try {
        const position = marker.getPosition();
        if (position && typeof position.lng === 'number' && typeof position.lat === 'number') {
          const distance = calculateDistanceInMeters(
            customerLocation,
            { lng: position.lng, lat: position.lat }
          );
          if (!isNaN(distance)) {
            allDistances.push(distance);
          }
        }
      } catch (error) {
        console.warn('获取员工标记位置失败:', error);
      }
    });
    
    if (allDistances.length > 0) {
      const maxDistance = Math.max(...allDistances);
      const avgDistance = allDistances.reduce((a, b) => a + b, 0) / allDistances.length;
      
      const customerCenteredZoom = calculateCustomerCenteredZoom(maxDistance, avgDistance);
      map.setZoom(customerCenteredZoom);
    } else {
      map.setZoom(9);
    }
    
  } catch (error) {
    console.error('视野调整失败:', error);
    
    try {
      const fallbackCenter = new AMap.LngLat(
        props.customerLocation.lng,
        props.customerLocation.lat
      );
      map.setCenter(fallbackCenter);
      map.setZoom(9);
    } catch (fallbackError) {
      console.error('fallback设置也失败:', fallbackError);
      message.error('地图视野调整失败');
    }
  }
};

// 计算距离（米）
const calculateDistanceInMeters = (point1: { lng: number; lat: number }, point2: { lng: number; lat: number }): number => {
  if (!AMap) return 0;
  
  try {
    const lngLat1 = new AMap.LngLat(point1.lng, point1.lat);
    const lngLat2 = new AMap.LngLat(point2.lng, point2.lat);
    return lngLat1.distance(lngLat2);
  } catch (error) {
    console.error('距离计算失败:', error);
    return 0;
  }
};

// 计算最佳缩放级别
const calculateCustomerCenteredZoom = (maxDistance: number, avgDistance: number): number => {
  const effectiveDistance = Math.max(maxDistance, avgDistance * 1.5);
  
  if (effectiveDistance <= 300) {
    return 17;
  } else if (effectiveDistance <= 600) {
    return 16;
  } else if (effectiveDistance <= 1200) {
    return 15;
  } else if (effectiveDistance <= 2500) {
    return 14;
  } else if (effectiveDistance <= 5000) {
    return 13;
  } else if (effectiveDistance <= 10000) {
    return 12;
  } else if (effectiveDistance <= 25000) {
    return 11;
  } else if (effectiveDistance <= 50000) {
    return 10;
  } else if (effectiveDistance <= 100000) {
    return 9;
  } else {
    return 8;
  }
};

// 优化标记显示
const optimizeMarkersForZoom = (zoomLevel: number) => {
  const markers = map.getAllOverlays('marker');
  
  markers.forEach(marker => {
    if (zoomLevel < 12) {
      marker.setOptions({
        offset: new AMap.Pixel(-8, -8)
      });
    } else if (zoomLevel >= 16) {
      marker.setOptions({
        offset: new AMap.Pixel(-12, -12)
      });
    } else {
      marker.setOptions({
        offset: new AMap.Pixel(-10, -10)
      });
    }
  });
};

// 智能地图调整
const adjustMapCenterIntelligently = () => {
  if (!checkMapReady()) {
    return;
  }
  
  try {
    const customerLocation = props.customerLocation;
    const customerCenter = new AMap.LngLat(customerLocation.lng, customerLocation.lat);
    
    map.setCenter(customerCenter);
    
    if (allEmployees.value.length === 0) {
      map.setZoom(9);
      return;
    }
    
    const distances = allEmployees.value
      .filter(emp => emp.location && emp.location.lng && emp.location.lat)
      .map(emp => calculateDistanceInMeters(customerLocation, emp.location))
      .filter(distance => !isNaN(distance) && distance > 0);
    
    if (distances.length === 0) {
      map.setZoom(9);
      return;
    }
    
    const maxDistance = Math.max(...distances);
    const avgDistance = distances.reduce((a, b) => a + b, 0) / distances.length;
    
    let optimalZoom = calculateCustomerCenteredZoom(maxDistance, avgDistance);
    map.setZoom(optimalZoom);
    
  } catch (error) {
    console.error('地图调整失败:', error);
    
    try {
      const fallbackCenter = new AMap.LngLat(
        props.customerLocation.lng,
        props.customerLocation.lat
      );
      map.setCenter(fallbackCenter);
      map.setZoom(9);
    } catch (fallbackError) {
      console.error('fallback设置失败:', fallbackError);
      message.error('地图视野调整失败');
    }
  }
};

// 显示距离圈
const showDistanceCircles = () => {
  if (!checkMapReady()) {
    message.warning('地图未就绪，请稍候再试');
    return;
  }
  
  try {
    const existingCircles = map.getAllOverlays('circle');
    const existingTexts = map.getAllOverlays('text');
    existingCircles.forEach(circle => map.remove(circle));
    existingTexts.forEach(text => map.remove(text));
    
    clearCustomerToEmployeeLines();
    
    const customerLocation = props.customerLocation;
    const customerCenter = new AMap.LngLat(customerLocation.lng, customerLocation.lat);
    
    const distances = allEmployees.value
      .filter(emp => emp.location && emp.location.lng && emp.location.lat)
      .map(emp => calculateDistanceInMeters(customerLocation, emp.location))
      .filter(d => !isNaN(d) && d > 0);
    
    if (distances.length === 0) {
      const defaultCircles = [500, 1000, 2000, 5000];
      createDistanceCircles(customerCenter, defaultCircles);
      message.info('以客户为中心显示标准距离圈');
      return;
    }
    
    const maxDistance = Math.max(...distances);
    const minDistance = Math.min(...distances);
    const avgDistance = distances.reduce((a, b) => a + b, 0) / distances.length;
    
    const circleDistances = calculateOptimalCircleDistances(maxDistance, minDistance, avgDistance);
    createDistanceCircles(customerCenter, circleDistances);
    
    const circleInfo = circleDistances.map(d => 
      d >= 1000 ? `${(d/1000).toFixed(1)}km` : `${d}m`
    ).join(', ');
    
    message.success(`以客户为中心显示${circleDistances.length}个距离圈: ${circleInfo}`);
    map.setCenter(customerCenter);
    
  } catch (error) {
    console.error('显示距离圈失败:', error);
    message.error('显示距离圈失败');
  }
};

// 计算最佳距离圈
const calculateOptimalCircleDistances = (maxDistance: number, minDistance: number, avgDistance: number): number[] => {
  const circles: number[] = [];
  
  if (maxDistance <= 1000) {
    circles.push(200, 500, 800);
  } else if (maxDistance <= 3000) {
    circles.push(500, 1000, 2000);
  } else if (maxDistance <= 10000) {
    circles.push(1000, 3000, 5000, 8000);
  } else if (maxDistance <= 25000) {
    circles.push(5000, 10000, 15000, 20000);
  } else {
    circles.push(10000, 25000, 50000);
  }
  
  return circles.filter(distance => distance <= maxDistance * 1.2);
};

// 创建距离圈
const createDistanceCircles = (center: any, distances: number[]) => {
  distances.forEach((radius, index) => {
    const circle = new AMap.Circle({
      center: center,
      radius: radius,
      strokeColor: '#1890ff',
      strokeOpacity: 0.4 - index * 0.06,
      strokeWeight: 2,
      fillColor: '#1890ff',
      fillOpacity: 0.08 - index * 0.015,
      zIndex: 20 - index,
      clickable: false
    });
    
    map.add(circle);
    
    const labelText = radius >= 1000 ? `${(radius / 1000).toFixed(1)}km` : `${radius}m`;
    const labelPosition = new AMap.LngLat(
      center.lng + radius / 111320 * 0.7,
      center.lat + radius / 111320 * 0.3
    );
    
    const label = new AMap.Text({
      text: labelText,
      position: labelPosition,
      style: {
        fontSize: '12px',
        fontWeight: 'bold',
        color: '#1890ff',
        backgroundColor: 'rgba(255,255,255,0.9)',
        padding: '2px 6px',
        borderRadius: '4px',
        border: '1px solid #1890ff',
        textAlign: 'center'
      },
      zIndex: 30
    });
    
    map.add(label);
  });
  
  const centerLabel = new AMap.Text({
    text: '📍 客户位置',
    position: center,
    style: {
      fontSize: '14px',
      fontWeight: 'bold',
      color: '#ff4d4f',
      backgroundColor: 'rgba(255,255,255,0.95)',
      padding: '4px 8px',
      borderRadius: '6px',
      border: '2px solid #ff4d4f',
      textAlign: 'center'
    },
    offset: new AMap.Pixel(0, -40),
    zIndex: 35
  });
  
  map.add(centerLabel);
};

// 获取当前位置
const getCurrentLocation = async () => {
  if (!navigator.geolocation) {
    message.error('您的浏览器不支持地理定位');
    return;
  }

  locationLoading.value = true;
  try {
    const position = await new Promise<GeolocationPosition>((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(resolve, reject);
    });

    const { latitude, longitude } = position.coords;
    
    if (map) {
      map.setCenter([longitude, latitude]);
      map.setZoom(15);
    }
    
    message.success('定位成功');
  } catch (error) {
    message.error('定位失败');
  } finally {
    locationLoading.value = false;
  }
};

// 重新定位客户
const relocateCustomer = async () => {
  if (!props.customerAddress || props.customerAddress.trim() === '') {
    message.warning('客户地址信息为空，无法进行定位');
    return;
  }
  
  try {
    locationLoading.value = true;
    message.info('正在重新定位客户地址...');
    
    // 调用地理编码服务
    await performGeocoding(props.customerAddress);
    message.success(`客户地址重新定位成功: ${props.customerAddress}`);
    
    // 如果地图已初始化，更新地图显示
    if (map && checkMapReady()) {
      // 等待一下让坐标更新完成，因为performGeocoding会触发事件更新父组件的坐标
      setTimeout(() => {
        // 坐标已通过事件更新到父组件，这里需要用最新的坐标
        const newCenter = new AMap.LngLat(props.customerLocation.lng, props.customerLocation.lat);
        map.setCenter(newCenter);
        map.setZoom(15);
        
        // 重新加载地图标记
        map.clearMap();
        clearCustomerToEmployeeLines();
        addCustomerMarker();
        
        // 重新加载员工位置，计算新的距离
        setTimeout(() => {
          loadEmployeeLocations();
        }, 200);
      }, 800); // 增加等待时间确保坐标完全更新
    }
    
  } catch (error) {
    console.error('重新定位失败:', error);
    message.error('客户地址重新定位失败，请检查地址信息是否正确');
  } finally {
    locationLoading.value = false;
  }
};

// 刷新员工位置
const refreshEmployeeLocations = () => {
  loadEmployeeLocations();
};

// 坐标验证
const validateCoordinates = () => {
  console.log('=== 坐标验证开始 ===');
  
  try {
    console.log('客户位置:', props.customerLocation);
    console.log('客户地址:', props.customerAddress);
    console.log('高德地图API状态:', !!AMap);
    console.log('地图实例状态:', !!map);
    
    if (map) {
      try {
        const mapCenter = map.getCenter();
        const mapZoom = map.getZoom();
        console.log('地图中心:', mapCenter.lng, mapCenter.lat);
        console.log('地图缩放级别:', mapZoom);
      } catch (mapError) {
        console.error('获取地图信息失败:', mapError);
      }
    }
    
    console.log('员工数据总数:', allEmployees.value.length);
    if (allEmployees.value.length > 0) {
      let validLocationCount = 0;
      let invalidLocationCount = 0;
      
      allEmployees.value.forEach((emp) => {
        if (emp.hasValidLocation && emp.location) {
          const isValidLocation = typeof emp.location.lng === 'number' && 
                                 typeof emp.location.lat === 'number' &&
                                 !isNaN(emp.location.lng) && 
                                 !isNaN(emp.location.lat);
          
          const inValidRange = emp.location.lng >= 73 && emp.location.lng <= 135 && 
                              emp.location.lat >= 3 && emp.location.lat <= 54;
          
          if (isValidLocation && inValidRange) {
            validLocationCount++;
          } else {
            invalidLocationCount++;
          }
          
          console.log(`- ${emp.realName}: ${emp.location.lng}, ${emp.location.lat}, 距离: ${emp.distance}, 有效: ${isValidLocation && inValidRange}`);
        } else {
          console.log(`- ${emp.realName}: 无位置信息`);
          invalidLocationCount++;
        }
      });
      
      console.log(`坐标统计: 有效 ${validLocationCount} 个, 无效 ${invalidLocationCount} 个`);
    }
    
    const customerValid = typeof props.customerLocation.lng === 'number' &&
                         typeof props.customerLocation.lat === 'number' &&
                         !isNaN(props.customerLocation.lng) &&
                         !isNaN(props.customerLocation.lat);
    
    console.log('客户坐标有效性:', customerValid);
    
    if (customerValid) {
      const { lng, lat } = props.customerLocation;
      const inChina = lng >= 73 && lng <= 135 && lat >= 18 && lat <= 54;
      console.log('坐标是否在中国境内:', inChina);
      
      if (!inChina) {
        console.warn('⚠️ 坐标超出中国范围，可能存在问题');
        message.warning('客户坐标超出中国范围，请检查地址信息');
      }
    } else {
      console.error('❌ 客户坐标数据无效');
      message.error('客户坐标数据无效');
    }
    
    console.log('=== 坐标验证完成 ===');
    
    const summary = `
验证完成：
• 客户坐标：${customerValid ? '✅ 有效' : '❌ 无效'}
• 地图状态：${checkMapReady() ? '✅ 就绪' : '❌ 未就绪'}  
• 员工数量：${allEmployees.value.length}个
    `.trim();
    
    message.info(summary);
    
  } catch (error) {
    console.error('坐标验证过程出错:', error);
    message.error('坐标验证失败');
  }
};

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
};

// 员工点击处理
const handleEmployeeClick = (employee: any) => {
  // 点击员工行，不执行任何操作，由按钮处理具体的选择逻辑
};

// 选择员工
const handleSelectEmployee = (employee: any) => {
  if (props.selectionMode === 'assignee') {
    if (props.selectedAssignee === employee.id) {
      message.info(`${employee.realName} 已是负责人`);
      return;
    }
    
    emit('select-assignee', employee);
    emit('update:selectedAssignee', employee.id);
    message.success(`已选择 ${employee.realName} 为负责人`);
  }
};


// 选择为负责人
const handleSelectAsAssignee = (employee: any) => {
  if (props.selectedAssignee === employee.id) {
    message.info(`${employee.realName} 已是负责人`);
    return;
  }
  
  emit('select-assignee', employee);
  emit('update:selectedAssignee', employee.id);
  message.success(`已选择 ${employee.realName} 为负责人`);
};

// 选择为协同人员
const handleSelectAsCollaborator = (employee: any) => {
  console.log('handleSelectAsCollaborator 被调用:', employee.realName, employee.id);
  console.log('当前协同人员列表:', props.selectedCollaborators);
  
  if (props.selectedCollaborators.includes(employee.id)) {
    message.info(`${employee.realName} 已是协同人员`);
    return;
  }
  
  emit('select-collaborator', employee);
  // 更新协同人员列表
  const newCollaborators = [...props.selectedCollaborators, employee.id];
  console.log('新的协同人员列表:', newCollaborators);
  emit('update:selectedCollaborators', newCollaborators);
  message.success(`已选择 ${employee.realName} 为协同人员`);
};


// 检查是否可以选择员工
const canSelectEmployee = (employee: any) => {
  if (props.selectionMode !== 'assignee') {
    return false;
  }
  
  return true;
};

// 获取选择按钮文本（非assignee模式）
const getSelectButtonText = (employee: any) => {
  if (props.selectionMode !== 'assignee') {
    return '当前派单方式不支持选择';
  }
  
  if (props.selectedAssignee === employee.id) {
    return '已选为负责人';
  }
  
  return '选为负责人';
};

// 检查员工是否已选择
const isEmployeeSelected = (employeeId: string) => {
  return props.selectedAssignee === employeeId || props.selectedCollaborators.includes(employeeId);
};

// 获取当前执行人角色
const getCurrentExecutorRole = (employeeId: string) => {
  const executor = props.currentExecutors.find(e => e.userId === employeeId);
  if (!executor) return '';
  
  if (executor.isResponsible) {
    return '当前负责人';
  } else {
    return '当前协同人';
  }
};

// 获取拒绝信息
const getRejectedInfo = (employeeId: string) => {
  return props.rejectedUsers.find(r => r.userId === employeeId) || null;
};

// 工具函数
const getStatusColor = (status: string) => {
  const colors = {
    available: 'green',
    busy: 'orange',
    offline: 'red'
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts = {
    available: '空闲',
    busy: '忙碌',
    offline: '离线'
  };
  return texts[status] || '未知';
};

const getAvatarColor = (status: string) => {
  const colors = {
    available: '#52c41a',
    busy: '#faad14',
    offline: '#ff4d4f'
  };
  return colors[status] || '#1890ff';
};

// 格式化日期时间
const formatDateTime = (dateTimeString: string) => {
  if (!dateTimeString) return '';
  
  try {
    const date = new Date(dateTimeString);
    
    if (isNaN(date.getTime())) {
      return dateTimeString;
    }
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  } catch (error) {
    console.error('日期格式化失败:', error);
    return dateTimeString;
  }
};

// 从地图选择员工为负责人的全局函数
const selectAsAssigneeFromMap = (employeeId: string) => {
  const employee = allEmployees.value.find(emp => emp.id === employeeId);
  if (employee) {
    handleSelectAsAssignee(employee);
    if (map) {
      map.clearInfoWindow();
    }
  }
};

// 从地图选择员工为协同人的全局函数
const selectAsCollaboratorFromMap = (employeeId: string) => {
  const employee = allEmployees.value.find(emp => emp.id === employeeId);
  if (employee) {
    handleSelectAsCollaborator(employee);
    if (map) {
      map.clearInfoWindow();
    }
  }
};

// 从地图移除员工选择的全局函数
const removeSelectionFromMap = (employeeId: string) => {
  const employee = allEmployees.value.find(emp => emp.id === employeeId);
  if (employee) {
    // 移除负责人身份
    if (props.selectedAssignee === employeeId) {
      emit('update:selectedAssignee', '');
      message.success(`已移除负责人 ${employee.realName}`);
    }
    
    // 移除协同人员身份
    if (props.selectedCollaborators.includes(employeeId)) {
      const newCollaborators = props.selectedCollaborators.filter(id => id !== employeeId);
      emit('update:selectedCollaborators', newCollaborators);
      message.success(`已移除协同人员 ${employee.realName}`);
    }
    
    if (map) {
      map.clearInfoWindow();
    }
  }
};

// 从地图选择员工的全局函数（兼容旧版本）
const selectEmployeeFromMap = (employeeId: string) => {
  const employee = allEmployees.value.find(emp => emp.id === employeeId);
  if (employee) {
    handleSelectEmployee(employee);
    if (map) {
      map.clearInfoWindow();
    }
  }
};

// 将函数挂载到全局对象上
if (typeof window !== 'undefined') {
  (window as any).selectEmployeeFromMap = selectEmployeeFromMap;
  (window as any).selectAsAssigneeFromMap = selectAsAssigneeFromMap;
  (window as any).selectAsCollaboratorFromMap = selectAsCollaboratorFromMap;
  (window as any).removeSelectionFromMap = removeSelectionFromMap;
}

// 监听视图模式变化
watch(viewMode, (newMode) => {
  if (newMode === 'map') {
    nextTick(() => {
      initMap();
    });
  }
});

// 监听客户位置变化
watch(() => props.customerLocation, () => {
  if (map) {
    map.setCenter([props.customerLocation.lng, props.customerLocation.lat]);
    map.clearMap();
    addCustomerMarker();
    loadEmployeeLocations();
  }
}, { deep: true });

// 监听props变化，更新视图
watch(() => props.selectedCollaborators, (newVal, oldVal) => {
  console.log('EmployeeLocationPicker props.selectedCollaborators 变化:', oldVal, '->', newVal);
}, { immediate: true, deep: true });

watch(() => props.selectedAssignee, (newVal, oldVal) => {
  console.log('EmployeeLocationPicker props.selectedAssignee 变化:', oldVal, '->', newVal);
}, { immediate: true });

// 生命周期
onMounted(async () => {
  console.log('EmployeeLocationPicker 挂载时的 props.selectedCollaborators:', props.selectedCollaborators);
  console.log('EmployeeLocationPicker 挂载时的 props.selectedAssignee:', props.selectedAssignee);
  
  await loadEmployeeLocations();
  
  if (viewMode.value === 'map') {
    nextTick(() => {
      initMap();
    });
  }
});

onUnmounted(() => {
  if (map) {
    map.destroy();
    map = null;
  }
  AMap = null;
  
  // 清理全局函数
  if (typeof window !== 'undefined') {
    delete (window as any).selectEmployeeFromMap;
  }
});
</script>

<style lang="less" scoped>
.employee-location-picker {
  .location-header {
    margin-bottom: 16px;
    display: flex;
    justify-content: flex-end;
  }

  .map-container {
    position: relative;
    
    .map-header {
      background: linear-gradient(135deg, #f5f9ff 0%, #eef6ff 100%);
      padding: 12px 16px;
      border-radius: 6px;
      border: 1px solid #d9e6ff;
      margin-bottom: 16px;

      h4 {
        display: flex;
        align-items: center;
        
        small {
          font-size: 12px;
          opacity: 0.8;
        }
      }
    }
    
    .map-controls {
      margin-bottom: 16px;
    }
    
    .map-view {
      width: 100%;
      height: 500px;
      border: 1px solid #d9d9d9;
      border-radius: 6px;
    }
    
    .map-legend {
      display: flex;
      gap: 24px;
      margin-top: 16px;
      padding: 12px;
      background: #fafafa;
      border-radius: 6px;
      
      .legend-item {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .legend-icon {
          width: 16px;
          height: 16px;
          border-radius: 50%;
          
          &.customer {
            background: #ff4d4f;
          }
          
          &.employee {
            &.available {
              background: #52c41a;
            }
            
            &.busy {
              background: #faad14;
            }
            
            &.selected {
              background: #1890ff;
            }
          }
        }
        
        .legend-text {
          font-size: 12px;
          color: #595959;
        }
      }
    }
  }
  
  .list-container {
    .list-controls {
      margin-bottom: 16px;
    }
    
  .employee-list {
    .selected-employee {
      background: #e6f7ff;
      border: 1px solid #91d5ff;
      border-radius: 6px;
      margin-bottom: 8px;
      
      &.assignee-selected {
        background: #f6ffed;
        border: 1px solid #b7eb8f;
        
        .ant-list-item-meta-title {
          color: #1890ff;
          font-weight: 500;
        }
      }
      
      &.collaborator-selected {
        background: #fff7e6;
        border: 1px solid #ffd591;
        
        .ant-list-item-meta-title {
          color: #52c41a;
          font-weight: 500;
        }
      }
    }
    
    // 如果同时是负责人和协同人（理论上不应该出现，但防护一下）
    .assignee-selected.collaborator-selected {
      background: linear-gradient(135deg, #f6ffed 0%, #fff7e6 100%);
      border: 1px solid #52c41a;
    }
      
      .employee-title {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .employee-name {
          font-weight: 500;
        }
      }
      
      .employee-info {
        .info-row {
          display: flex;
          align-items: center;
          gap: 6px;
          margin-bottom: 4px;
          font-size: 12px;
          color: #8c8c8c;
          
          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}
</style>
